package com.newlink.building.secret.utils

import android.graphics.Bitmap
import android.graphics.Canvas
import android.util.Log
import android.view.View
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * Created by xiaodong on 2022/10/8.
 */
object Module_Secret_BitmapUtils {

    fun saveViewBitmapToFile(view: View?, filePath: String): Boolean {
        val screenshotBitmap = loadBitmapFromView(view)
        Log.d("BitmapUtils", "filePath:$filePath")
        val file = File(filePath)
        return try {
            if (!file.exists()) {
                file.createNewFile()
            }
            val bos = BufferedOutputStream(FileOutputStream(file))
            screenshotBitmap?.compress(Bitmap.CompressFormat.JPEG, 100, bos)
            bos.flush()
            bos.close()
            true
        } catch (e: IOException) {
            e.printStackTrace()
            false
        }

        return false
    }

    fun saveBitmapToFile(bitmap: Bitmap?, filePath: String): Boolean {
        Log.d("BitmapUtils", "filePath:$filePath")
        val file = File(filePath)
        return try {
            if (!file.exists()) {
                file.createNewFile()
            }
            val bos = BufferedOutputStream(FileOutputStream(file))
            bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, bos)
            bos.flush()
            bos.close()
            true
        } catch (e: IOException) {
            e.printStackTrace()
            false
        }

        return false
    }

    fun loadBitmapFromView(v: View?): Bitmap? {
        if (v == null) {
            return null
        }
        val screenshot: Bitmap = Bitmap.createBitmap(v.width, v.height, Bitmap.Config.ARGB_8888)
        val c = Canvas(screenshot)
        v.draw(c)
        return screenshot
    }

    fun captureView(view: View): Bitmap? {

        // 保存原始的布局参数
        val originalLeft = view.left
        val originalTop = view.top
        val originalRight = view.right
        val originalBottom = view.bottom

        view.measure(
            View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        )
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        // 创建 Bitmap 并绘制
        val bitmap = Bitmap.createBitmap(
            view.measuredWidth,
            view.measuredHeight,
            Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(bitmap)
        view.draw(canvas)

        // 恢复原始的布局参数
        view.layout(originalLeft, originalTop, originalRight, originalBottom)
        return bitmap
    }
}